<?php
declare (strict_types = 1);

namespace app\patient\controller;

use app\Db2;
use think\response\Json;
use think\facade\Request;
use app\AppAuthController;
use EasyWeChat\Factory;

// class Pay extends AppAuthController
class Pay
{
    public function place_an_order()
    {
        $user = check_login(Request::header('Authorization'));
        $config = [
            // 必要配置
            'app_id'             => 'wx485998504983c8a1',
            'mch_id'             => '1646284594',
            'key'                => '7e1e85f1d56e05fd3febcafdbdf003c4',   // API v2 密钥 (注意: 是v2密钥 是v2密钥 是v2密钥)
        ];

        $app = Factory::payment($config);

        $result = $app->order->unify([
            'body' => '医康宝',
            'out_trade_no' => '20150806125357',
            'total_fee' => 1,
            'notify_url' => 'https://ykbwxapp.icanbo.com.cn/index.php/patient/pay/notify_url',     // 你也可以在下单时单独设置来想覆盖它
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $user['wx_app_openid'],
        ]);

        if (isset($result['err_code'])) {
            return rejson(0,'参数错误，请重新下单', $data);
        } else {
            $jssdk = $app->jssdk;
            $config = $jssdk->sdkConfig($result['prepay_id']);
            $config['timeStamp'] = $config['timestamp'];//此处需要将小写s变为大写

            return rejson(200,'操作成功', $config);
        }
    }
    
    public function notify_url(){
        // 1. 验证回调的合法性
        $wechatPayKey = '7e1e85f1d56e05fd3febcafdbdf003c4'; // 你的微信支付API密钥
        $xmlData = file_get_contents('php://input'); // 从HTTP请求中获取XML数据
        $data = simplexml_load_string($xmlData, 'SimpleXMLElement', LIBXML_NOCDATA);
        if ($data === false) {
            die('Invalid XML');
        }
        
        $sign = $data->sign;
        unset($data->sign);
        $signData = [];
        foreach ($data as $key => $value) {
            $signData[$key] = (string) $value;
        }
        ksort($signData);
        $signString = urldecode(http_build_query($signData));
        $signString .= '&key=' . $wechatPayKey;
        $hashedString = strtoupper(md5($signString));
        
        if ($hashedString !== $sign) {
            die('Signature verification failed');
        }
        
        // 2. 处理支付结果
        if ($data->return_code === 'SUCCESS' && $data->result_code === 'SUCCESS') {
            // 支付成功，处理你的业务逻辑，例如更新订单状态、记录支付信息等
            $outTradeNo = $data->out_trade_no;
            // TODO: 执行相关操作
            echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>'; // 告知微信支付回调已成功接收
            log2(json_encode($data));
            $list = Db2::insert_data('article',['text'=>json_encode($data)]);
        } else {
            // 支付失败
            echo '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[Payment failed]]></return_msg></xml>';
        }
    }
}


